// pages/teacher/kaoqin/detail/detail.js
Page({
  data: {
    attendanceId: null,
    courseId: null,
    attendanceInfo: null,
    studentList: [],
    isLoading: true,
    statusFilter: 'all', // all, present, absent, leave
    stats: {
      total: 0,
      present: 0,
      absent: 0,
      leave: 0
    }
  },

  onLoad: function(options) {
    if (options.id) {
      this.setData({
        attendanceId: options.id,
        courseId: options.courseId || null
      });
      this.fetchAttendanceDetail();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },
  
  // 获取考勤详情
  fetchAttendanceDetail: function() {
    const attendanceId = this.data.attendanceId;
    
    console.log('正在获取考勤详情，ID:', attendanceId);
    
    wx.request({
      url: `http://localhost:3000/api/teacher/attendance/${attendanceId}`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        console.log('考勤详情响应状态码:', res.statusCode);
        console.log('考勤详情响应完整数据:', res.data);
        
        if (res.statusCode === 200 && res.data.success) {
          const sessionData = res.data.data;
          
          // 直接使用服务器返回的数据，不再请求额外的统计数据
          if (sessionData && sessionData.attendanceInfo) {
            const attendanceInfo = sessionData.attendanceInfo;
            const stats = sessionData.stats || {};
            
            // 检查原始数据中的位置相关字段
            console.log('考勤信息中的位置相关字段:');
            console.log('- location:', attendanceInfo.location);
            console.log('- address:', attendanceInfo.address);
            console.log('- latitude:', attendanceInfo.latitude);
            console.log('- longitude:', attendanceInfo.longitude);
            
            // 处理位置信息
            let locationText = '未指定地点';
            
            // 尝试从各种可能的字段获取位置信息
            if (attendanceInfo.address) {
              try {
                // 如果address是JSON字符串，尝试解析
                if (typeof attendanceInfo.address === 'string' && attendanceInfo.address.startsWith('{')) {
                  const addressObj = JSON.parse(attendanceInfo.address);
                  locationText = addressObj.address || locationText;
                } else {
                  locationText = attendanceInfo.address;
                }
              } catch (e) {
                console.error('解析地址信息失败:', e);
                locationText = attendanceInfo.address; // 如果解析失败，直接使用原始字符串
              }
            } else if (attendanceInfo.location) {
              // 如果没有address字段，尝试使用location字段
              try {
                if (typeof attendanceInfo.location === 'string' && attendanceInfo.location.startsWith('{')) {
                  const locationObj = JSON.parse(attendanceInfo.location);
                  locationText = locationObj.address || locationText;
                } else {
                  locationText = attendanceInfo.location;
                }
              } catch (e) {
                console.error('解析位置信息失败:', e);
                locationText = attendanceInfo.location;
              }
            }
            
            console.log('最终解析的位置文本:', locationText);
            
            // 更新考勤详情和统计数据
            this.setData({
              attendanceInfo: {
                ...attendanceInfo,
                location: locationText,
                totalCount: stats.total || 0,
                presentCount: stats.present || 0,
                absentCount: stats.absent || 0,
                leaveCount: stats.leave || 0
              },
              studentList: sessionData.studentList || [],
              stats: {
                total: stats.total || 0,
                present: stats.present || 0,
                absent: stats.absent || 0,
                leave: stats.leave || 0
              },
              isLoading: false
            });
          } else {
            // 处理数据结构不符合预期的情况
            this.setData({
              attendanceInfo: sessionData.attendanceInfo || {},
              studentList: sessionData.studentList || [],
              stats: sessionData.stats || {
                total: 0,
                present: 0,
                absent: 0,
                leave: 0
              },
              isLoading: false
            });
          }
        } else {
          this.setData({
            isLoading: false
          });
          wx.showToast({
            title: res.data.message || '获取考勤详情失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取考勤详情失败:', err);
        this.setData({
          isLoading: false
        });
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },
  
  // 切换状态筛选
  changeStatusFilter: function(e) {
    const status = e.currentTarget.dataset.status;
    this.setData({
      statusFilter: status
    });
  },
  
  // 导出考勤记录
  exportAttendance: function() {
    // 保持原有代码不变
  },
  
  // 结束考勤
  endAttendance: function() {
    // 保持原有代码不变
  },
  
  // 格式化时间
  formatTime: function(date) {
    // 保持原有代码不变
  }
});